<?php

class ActivityDetailController extends Controller
{

	/**
     * 过滤器
	 * @return 返回值是一个存放过滤器的数组
	 */
	public function filters()
	{
		return array(
            'accessAuth',//自定义授权方式 
			//'accessControl', //默认授权方式
			'postOnly + delete',//删除操作只支持post请求
		);
	}
    /**
     * 自定义权限验证规则
     * @param type $filterChain
     * @throws CHttpException
     */
    public function filterAccessAuth($filterChain) {  
        if(Yii::app()->user->getIsGuest()) {  
            echo '<script>top.location.href="'.Yii::app()->user->returnUrl.'";</script>';
            exit;
        } else if(!Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())){
            throw new CHttpException(403,'无权访问此页面');
        }
        $filterChain->run();  
    }  
    /**
     * 页面白名单
     * @return type
     */
    public function authlessActions() {  
        return array(
            'index','admin','view','create','update','delete','delete_model','stop_model'
		); 
    }

	/**
	 * 查看页面
	 * @param integer $id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionCreate()
	{
		$modelA=new ActivityDetail;
                $modelB=new LineDetail;
		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['ActivityDetail']))
		{                        
			$modelA->attributes=$_POST['ActivityDetail'];
                        $transaction = Yii::app()->db->beginTransaction(); //创建事务
                        //判断是否是团体报名，如果是就添加5位没有数字4的邀请码
                        $is_float=$modelA->is_float;
//                        $modelC= Crowd::model()->findByPk($crowd_id);
//                        $title=$modelC->title;                          
                        if ($is_float==2){
                            $is_true=FALSE;
                            //判断邀请码是否重复
                            $rand='';
                            do{
                                $randStr = str_shuffle('123567890');
                                $rand = substr($randStr,0,5);
                                $a_count=ActivityDetail::model()->find("invitation_code='".$rand."'");
                                if(count($a_count)==0){
                                    $is_true=TRUE;
                                }
                            }while (!$is_true);
                            $modelA->invitation_code=$rand;
                        }
                        //添加线路安排
                        if($modelA->save()){                          
                           $modelB->attributes=$_POST['LineDetail']; 
                           $model_count = count($modelB->car_id);
                            for($i=0;$i<$model_count;$i++){
                                $c=new LineDetail();
                                $c->ad_id=$modelA->id;
                                if(empty($modelB->car_id[$i])){
                                    echo '{"Line_detail":["请选择车辆"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();                                      
                                }
                                $c->car_id=$modelB->car_id[$i];
                                if(empty($modelB->go_time[$i])){
                                    echo '{"Line_detail":["请选择上车时间"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                     
                                $c->go_time=$modelB->go_time[$i];     
                                if(empty($modelB->position_id[$i])){
                                    echo '{"Line_detail":["请选择上车地点"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                       
                                $c->position_id=$modelB->position_id[$i];  
                                if(empty($modelB->staff[$i])){
                                    echo '{"Line_detail":["请选择随车人员"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                
                                $c->staff=$modelB->staff[$i];     
                                $c->save();
                                }
                                echo 1;
                                $transaction->commit(); //提交事务
                                Yii::app()->end();
                                die();                                   
                            }  else {
                                echo CActiveForm::validate($modelA);//有错误信息返回给页面 
                                $transaction->rollback(); //回滚事务
                                Yii::app()->end();
                                die();   
                                                        
                            }                         
//                            Yii::app()->user->setFlash('success','操作成功！');                        
//                            $this->redirect(array('Activity/clander'));  
                                $transaction->commit(); //提交事务
                                Yii::app()->end();
                                die();       
                          
                        
//                         
//			if($model->save()){
//                            Yii::app()->user->setFlash('success','操作成功！');                        
//                            $this->redirect(array('Activity/clander'));
//                        }
		}
                $date='';
                if(isset($_GET['date'])){
                    $date=$_GET['date'];
                }
		$this->render('create',array(
			'modelA'=>$modelA,
                        'modelB'=>$modelB,
                        'date'=>$date,
		));
	}

	/**
	 * 修改页面
	 * 如果修改成功，跳转到查看页面
	 * @param integer $id 
	 */
	public function actionUpdate($id)
	{       
		$model=$this->loadModel($id);
                $sms_model=Sms::model()->find("activity_id=".$model->activity_id);
                $line_model=LineDetail::model()->findAll("ad_id=".$id);
                $modelB=new LineDetail;
		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['ActivityDetail']))
		{
                        $transaction = Yii::app()->db->beginTransaction(); //创建事务
			$model->attributes=$_POST['ActivityDetail'];
			if($model->save()){
                            //删除原有线路明细创建新的线路明细
                            if(!isset($_POST['LineDetail'])){
                                echo '{"Line_detail":["至少需要一个安排"]}';//有错误信息返回给页面
                                $transaction->rollback(); //回滚事务
                                Yii::app()->end();
                                die();                                   
                            }
                            $modelB->attributes=$_POST['LineDetail']; 
                            for($i=0;$i<count($modelB->car_id);$i++){
//                                $c=new LineDetail();
//                                if(!empty($_POST['LineDetail_id['.$i.']'])){
                                    $l_id=$_POST['LineDetail_id_'.$i];
                                    $c=LineDetail::model()->findByPk($l_id);
//                                }
//                                $c=new LineDetail();
//                                $c->id=$modelB->id[$i];
                                $c->ad_id=$model->id;
                                if(empty($modelB->car_id[$i])){
                                    echo '{"Line_detail":["请选择车辆"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();                                      
                                }
                                $c->car_id=$modelB->car_id[$i];
                                if(empty($modelB->go_time[$i])){
                                    echo '{"Line_detail":["请选择上车时间"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                     
                                $c->go_time=$modelB->go_time[$i];     
                                if(empty($modelB->position_id[$i])){
                                    echo '{"Line_detail":["请选择上车地点"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                       
                                $c->position_id=$modelB->position_id[$i];  
                                if(empty($modelB->staff[$i])){
                                    echo '{"Line_detail":["请选择随车人员"]}';//有错误信息返回给页面
                                    $transaction->rollback(); //回滚事务
                                    Yii::app()->end();
                                    die();   
                                }                                
                                $c->staff=$modelB->staff[$i];     
                                $c->save();
                                }
                                //删除线路明细
//                                $i=0;
//                                $line_id=array();
//                                foreach ($line_model as $value) {
//                                   $line_id[$i]=$value->id;
//                                   $i+=1;                             
//                                }
//                                $criteria= new CDbCriteria;
//                                $criteria->addInCondition('id', $line_id);
//                                LineDetail::model()->deleteAll($criteria);                                    
                                echo 1;
                                $transaction->commit(); //提交事务
                                Yii::app()->end();
                                die();                                   
//                                if(!empty($modelB->car_id[$i])){
//                                     $c=new LineDetail();
//                                     $c->ad_id=$id;
//                                     $c->car_id=$modelB->car_id[$i];
//                                     $c->go_time=$modelB->go_time[$i];
//                                     $c->position_id=$modelB->position_id[$i];
//                                     $c->staff=$modelB->staff[$i];
//                                     $c->save();
//                                }
                            }  
                            //
                            Yii::app()->user->setFlash('success','操作成功！');
                            $this->redirect(array('Activity/clander'));
                        }
		
                $connection = Yii::app()->db;
                //已报名人数
                $sql="SELECT (count(*)+ (SELECT COUNT(*) FROM party WHERE ad_id=".$id.")) as 'count' FROM children  WHERE party_id in (SELECT id FROM party WHERE ad_id=".$id.")";
//                $sql = "SELECT count(*) as count FROM party  WHERE ad_id = ".$id;
                $command_1 = $connection->createCommand($sql);  
                $result_1 = $command_1->queryAll();  
                $num_1=$result_1[0]['count'];    
                //已审核人数
                $sql="SELECT (count(*)+ (SELECT COUNT(*) FROM party WHERE is_float=1 AND ad_id=".$id.")) as 'count' FROM children  WHERE party_id in (SELECT id FROM party WHERE is_float=1 AND ad_id=".$id.")";
//                $sql = "SELECT count(*) as count FROM party  WHERE is_float=1 AND ad_id = ".$id;
                $command_2 = $connection->createCommand($sql);  
                $result_2 = $command_2->queryAll();  
                $num_2=$result_2[0]['count'];    
                
		$this->render('update',array(
			'model'=>$model,
                        'sms_model'=>$sms_model,
                        'line_model'=>$line_model,
                        'modelB'=>$modelB,
                        'num_1'=>$num_1,
                        'num_2'=>$num_2
		));
	}

	/**
	 * 删除功能
	 * 一般只接受post方式的异步提交
	 * @param integer $id 
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
            $id=$_POST['id'];
            //获取id数组批量删除
            $criteria= new CDbCriteria;
            $criteria->addInCondition('id', $id);
            $res=ActivityDetail::model()->deleteAll($criteria);
            //输出json结果
            echo CJSON::encode(array('result'=>$res));
        }else{
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } 
	}

	/**
	 * 列表页
	 */
	public function actionAdmin()
	{
		$model=new ActivityDetail('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['ActivityDetail']))
			$model->attributes=$_GET['ActivityDetail'];

		$this->render('admin',array(
			'model'=>$model,
			'data'=>$model->search(),
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return ActivityDetail the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=ActivityDetail::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param ActivityDetail $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='activity-detail-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        /**
         * 删除活动
         * @param type $id
         */
	public function actionDelete_model()
	{
            if(!empty($_GET['id'])){
                $id=$_GET['id'];   
                //查询用户表中是否添加该活动
                $connection = Yii::app()->db;
                $sql = "SELECT COUNT(*) AS count FROM party WHERE ad_id=".$id;
                $command = $connection->createCommand($sql);
                $result = $command->queryAll();  
                $num=$result[0]['count'];  
                if($num>0){
                    Yii::app()->user->setFlash('delete_error','不能删除已开始的活动！');
                    $this->redirect(array('activityDetail/update','id'=>$id));          
                    return;
                }
                //删除线路
                $line_detail=LineDetail::model()->findAll('ad_id='.$id);
                $line_id=array();
                $i=0;
                foreach ($line_detail as $value) {
                    $line_id[$i]=$value->id;
                    $i++;
                }
                $criteria_line= new CDbCriteria;
                $criteria_line->addInCondition('id', $line_id);
                $res_line=LineDetail::model()->deleteAll($criteria_line);
                
                $detail_id=array();
                $detail_id[0]=$id;
                //获取id数组批量删除
                $criteria= new CDbCriteria;
                $criteria->addInCondition('id', $detail_id);
                $res=ActivityDetail::model()->deleteAll($criteria);
                Yii::app()->user->setFlash('delete_success','删除成功！');
                $this->redirect(array('Activity/clander'));           
            }
	}  
        /**
         * 截止报名
         */
	public function actionStop_model()
	{
            if(isset($_GET['id'])){
                $id=$_GET['id']; 
                $connection = Yii::app()->db;
                //已报名人数UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson' 
                $sql = "UPDATE activity_detail SET is_float=3 WHERE id=".$id;
                $command = $connection->createCommand($sql);  
                $result=$command->execute(); 
                Yii::app()->user->setFlash('stop','当前活动已截止！');
                $this->redirect(array('activityDetail/update','id'=>$id));           
            }
	}          
}
